package com.online.customerchatserver.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by littleheng on 2018/4/28
 */
@Configuration
@MapperScan(basePackages = "com.online.customerchatserver.slave0", sqlSessionTemplateRef = "slave0SqlSessionTemplate")
public class OlsMod0DatasourceConfig {

    @Bean(name = "slave0DataSourceProperties")
    @Qualifier("slave0DataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.ols0")
    public DataSourceProperties slave0DataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * 配置数据数据源 ols0
     * @return
     */
    @Bean(name = "slave0Datasource")
    @ConfigurationProperties(prefix = "spring.datasource.ols0")
//    @Primary
    public DataSource slaveDatasource(){

        return slave0DataSourceProperties().initializeDataSourceBuilder().build();
    }

    /**
     * 配置session工厂
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "slave0SqlSessionFactory")
//    @Primary
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slave0Datasource") DataSource dataSource) throws  Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
//        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:"));
        return bean.getObject();
    }

    /**
     * 配置事务管理器
     * @param dataSource
     * @return
     */
    @Bean(name = "slave0TransactionManger")
//    @Primary
    public DataSourceTransactionManager slaveTransactionManger(@Qualifier("slave0Datasource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }


    /**
     * 模版
     * @param sqlSessionFactory
     * @return
     * @throws Exception
     */
    @Bean(name = "slave0SqlSessionTemplate")
//    @Primary
    public SqlSessionTemplate slaveSqlSessionTemplate(@Qualifier("slave0SqlSessionFactory")SqlSessionFactory sqlSessionFactory) throws Exception{
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}